<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : User session library
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class User_session_mobile {

  private $ci;

  public function __construct() {
    $this->ci = & get_instance();
  }

  // Sets the user id in the cache
  private function set_signin_user($session_id = NULL, $user_id = NULL) {
    return @$this->ci->cache->save($session_id, (int) $user_id, 32400);
  }

  // Gets the saved user id in the cache
  private function get_signin_user($session_id = NULL) {
    return (int) @$this->ci->cache->get($session_id);
  }

  // Unset all current user session
  private function del_signin_user($session_id = NULL) {
    return @$this->ci->cache->delete($session_id);
  }

  // Signing in the user
  // Calls the set user session method
  public function signin($username = NULL, $enc_password = NULL) {
    if (!empty($username) && !empty($enc_password) && ctype_alnum($enc_password)) {
      $get_user_by_password = $this->ci->user_model->get_user_by_password($username, $enc_password);
      if ($get_user_by_password['status'] == 1 && !empty($get_user_by_password['result'])) {
        if ($get_user_by_password['result']['user_resigned'] != 1) {
          $session_id = md5(rand(1111111111, 9999999999));
          $signing_in = $this->set_signin_user($session_id, $get_user_by_password['result']['user_id']);
          if ($signing_in) {
            return $session_id;
          }
        }
      }
    }
    return NULL;
  }

  // Signing out the user
  // Calls the clear user session method
  public function signout($session_id = NULL) {
    $this->del_signin_user($session_id);
  }

  // Returs user data if valid session
  // Update the current user last activity time
  public function signuser($session_id = NULL) {
    $user_id = $this->get_signin_user($session_id);
    if (!empty($user_id) && is_numeric($user_id)) {
      $get_user_by_id = $this->ci->user_model->get_user_by_id($user_id);
      if ($get_user_by_id['status'] == 1 && !empty($get_user_by_id['result'])) {
        $this->ci->user_model->update_online($user_id);
        return $get_user_by_id['result'];
      }
    }
    return NULL;
  }

}

?>
